// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#include <pollux/expression/vector_function.h>
#include <pollux/functions/lib/string_encoding_utils.h>
#include <pollux/common/strings/string_core.h>

namespace kumo::pollux::functions::sparksql {
    using namespace stringCore;

    namespace {
        template<bool isAscii>
        int32_t instr(
            const melon::StringPiece haystack,
            const melon::StringPiece needle) {
            int32_t offset = haystack.find(needle);
            if constexpr (isAscii) {
                return offset + 1;
            } else {
                // If the string is unicode, convert the byte offset to a codepoints.
                return offset == -1 ? 0 : lengthUnicode(haystack.data(), offset) + 1;
            }
        }

        class Instr : public exec::VectorFunction {
            bool ensureStringEncodingSetAtAllInputs() const override {
                return true;
            }

            void apply(
                const SelectivityVector &selected,
                std::vector<VectorPtr> &args,
                const TypePtr & /* outputType */,
                exec::EvalCtx &context,
                VectorPtr &result) const override {
                POLLUX_CHECK_EQ(args.size(), 2);
                POLLUX_CHECK_EQ(args[0]->type_kind(), TypeKind::VARCHAR);
                POLLUX_CHECK_EQ(args[1]->type_kind(), TypeKind::VARCHAR);
                exec::LocalDecodedVector haystack(context, *args[0], selected);
                exec::LocalDecodedVector needle(context, *args[1], selected);
                context.ensure_writable(selected, INTEGER(), result);
                auto *output = result->as<FlatVector<int32_t> >();

                if (isAscii(args[0].get(), selected)) {
                    selected.applyToSelected([&](vector_size_t row) {
                        auto h = haystack->value_at<StringView>(row);
                        auto n = needle->value_at<StringView>(row);
                        output->set(row, instr<true>(h, n));
                    });
                } else {
                    selected.applyToSelected([&](vector_size_t row) {
                        auto h = haystack->value_at<StringView>(row);
                        auto n = needle->value_at<StringView>(row);
                        output->set(row, instr<false>(h, n));
                    });
                }
            }
        };

        class Length : public exec::VectorFunction {
            bool ensureStringEncodingSetAtAllInputs() const override {
                return true;
            }

            void apply(
                const SelectivityVector &selected,
                std::vector<VectorPtr> &args,
                const TypePtr & /* outputType */,
                exec::EvalCtx &context,
                VectorPtr &result) const override {
                POLLUX_CHECK_EQ(args.size(), 1);
                POLLUX_CHECK(
                    args[0]->type_kind() == TypeKind::VARCHAR ||
                    args[0]->type_kind() == TypeKind::VARBINARY);
                exec::LocalDecodedVector input(context, *args[0], selected);
                context.ensure_writable(selected, INTEGER(), result);
                auto *output = result->as<FlatVector<int32_t> >();

                if (args[0]->type_kind() == TypeKind::VARCHAR &&
                    !isAscii(args[0].get(), selected)) {
                    selected.applyToSelected([&](vector_size_t row) {
                        const StringView str = input->value_at<StringView>(row);
                        output->set(row, lengthUnicode(str.data(), str.size()));
                    });
                } else {
                    selected.applyToSelected([&](vector_size_t row) {
                        output->set(row, input->value_at<StringView>(row).size());
                    });
                }
            }
        };
    } // namespace

    std::vector<std::shared_ptr<exec::FunctionSignature> > instrSignatures() {
        return {
            exec::FunctionSignatureBuilder()
            .returnType("INTEGER")
            .argumentType("VARCHAR")
            .argumentType("VARCHAR")
            .build(),
        };
    }

    std::shared_ptr<exec::VectorFunction> makeInstr(
        const std::string &name,
        const std::vector<exec::VectorFunctionArg> &inputArgs,
        const core::QueryConfig & /*config*/) {
        static const auto kInstrFunction = std::make_shared<Instr>();
        return kInstrFunction;
    }

    std::vector<std::shared_ptr<exec::FunctionSignature> > lengthSignatures() {
        return {
            exec::FunctionSignatureBuilder()
            .returnType("INTEGER")
            .argumentType("VARCHAR")
            .build(),
            exec::FunctionSignatureBuilder()
            .returnType("INTEGER")
            .argumentType("VARBINARY")
            .build(),
        };
    }

    std::shared_ptr<exec::VectorFunction> makeLength(
        const std::string &name,
        const std::vector<exec::VectorFunctionArg> &inputArgs,
        const core::QueryConfig & /*config*/) {
        static const auto kLengthFunction = std::make_shared<Length>();
        return kLengthFunction;
    }

    void encodeDigestToBase16(uint8_t *output, int digestSize) {
        static unsigned char const kHexCodes[] = "0123456789abcdef";
        for (int i = digestSize - 1; i >= 0; --i) {
            int digestChar = output[i];
            output[i * 2] = kHexCodes[(digestChar >> 4) & 0xf];
            output[i * 2 + 1] = kHexCodes[digestChar & 0xf];
        }
    }
} // namespace kumo::pollux::functions::sparksql
